#include "concurrent_player_test.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <fstream>

void print_usage() {
    std::cout << "Usage: concurrent_player_test [options]" << std::endl;
    std::cout << "Options:" << std::endl;
    std::cout << "  --players <num>           Number of concurrent players (default: 1000000)" << std::endl;
    std::cout << "  --rps <num>              Requests per second per player (default: 5)" << std::endl;
    std::cout << "  --duration <seconds>     Test duration in seconds (default: 30)" << std::endl;
    std::cout << "  --find-max               Find maximum players automatically" << std::endl;
    std::cout << "  --benchmark-suite        Run comprehensive benchmark suite" << std::endl;
    std::cout << "  --max-latency <ms>       Maximum acceptable latency in ms (default: 100)" << std::endl;
    std::cout << "  --min-success-rate <rate> Minimum success rate (default: 0.95)" << std::endl;
    std::cout << "  --help                   Show this help message" << std::endl;
    std::cout << std::endl;
    std::cout << "Examples:" << std::endl;
    std::cout << "  concurrent_player_test --players 1000000 --rps 5 --duration 30" << std::endl;
    std::cout << "  concurrent_player_test --find-max --rps 5 --duration 30" << std::endl;
    std::cout << "  concurrent_player_test --benchmark-suite" << std::endl;
}

void save_results_to_file(const std::string& filename, const std::string& results) {
    std::ofstream file(filename);
    if (file.is_open()) {
        file << results;
        file.close();
        std::cout << "Results saved to: " << filename << std::endl;
    } else {
        std::cerr << "Failed to save results to: " << filename << std::endl;
    }
}

std::string get_timestamp() {
    auto now = std::chrono::system_clock::now();
    auto time_t = std::chrono::system_clock::to_time_t(now);
    std::stringstream ss;
    ss << std::put_time(std::localtime(&time_t), "%Y%m%d_%H%M%S");
    return ss.str();
}

int main(int argc, char* argv[]) {
    std::cout << "=== HTTP Library Concurrent Player Performance Test ===" << std::endl;
    std::cout << "Test Time: " << std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::system_clock::now().time_since_epoch()).count() << std::endl;
    std::cout << "System Info: " << std::endl;
    std::cout << "  CPU Cores: " << std::thread::hardware_concurrency() << std::endl;
    std::cout << "  Platform: " << 
#ifdef __linux__
        "Linux"
#elif __APPLE__
        "macOS"
#elif _WIN32
        "Windows"
#else
        "Unknown"
#endif
        << std::endl;
    std::cout << std::endl;
    
    // 默认参数
    int num_players = 1000000;  // 默认100万玩家
    int requests_per_second = 5;  // 每秒5次请求
    int test_duration_seconds = 30;  // 30秒测试时间
    bool find_max_mode = false;
    bool benchmark_suite_mode = false;
    double max_latency_ms = 100.0;
    double min_success_rate = 0.95;
    
    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        std::string arg = argv[i];
        if (arg == "--players" && i + 1 < argc) {
            num_players = std::stoi(argv[++i]);
        } else if (arg == "--rps" && i + 1 < argc) {
            requests_per_second = std::stoi(argv[++i]);
        } else if (arg == "--duration" && i + 1 < argc) {
            test_duration_seconds = std::stoi(argv[++i]);
        } else if (arg == "--find-max") {
            find_max_mode = true;
        } else if (arg == "--benchmark-suite") {
            benchmark_suite_mode = true;
        } else if (arg == "--max-latency" && i + 1 < argc) {
            max_latency_ms = std::stod(argv[++i]);
        } else if (arg == "--min-success-rate" && i + 1 < argc) {
            min_success_rate = std::stod(argv[++i]);
        } else if (arg == "--help") {
            print_usage();
            return 0;
        }
    }
    
    // 显示测试配置
    std::cout << "Test Configuration:" << std::endl;
    std::cout << "  Players: " << num_players << std::endl;
    std::cout << "  Requests/second/player: " << requests_per_second << std::endl;
    std::cout << "  Total QPS: " << (num_players * requests_per_second) << std::endl;
    std::cout << "  Duration: " << test_duration_seconds << " seconds" << std::endl;
    std::cout << "  Max acceptable latency: " << max_latency_ms << "ms" << std::endl;
    std::cout << "  Min success rate: " << (min_success_rate * 100) << "%" << std::endl;
    std::cout << "  Mode: " << (find_max_mode ? "Find Maximum Players" : 
                                  (benchmark_suite_mode ? "Benchmark Suite" : "Standard Test")) << std::endl;
    std::cout << std::endl;
    
    // 创建测试实例
    ConcurrentPlayerTest test;
    
    // 捕获测试输出
    std::streambuf* orig_cout = std::cout.rdbuf();
    std::ostringstream captured_output;
    
    try {
        // 设置服务器
        if (!test.setup_server()) {
            std::cerr << "Failed to setup test server" << std::endl;
            return 1;
        }
        
        // 运行测试
        if (benchmark_suite_mode) {
            std::cout << "Running comprehensive benchmark suite..." << std::endl;
            test.run_benchmark_suite();
        } else if (find_max_mode) {
            std::cout << "Finding maximum concurrent players..." << std::endl;
            test.find_max_players(requests_per_second, test_duration_seconds, max_latency_ms, min_success_rate);
        } else {
            std::cout << "Running standard concurrent player test..." << std::endl;
            
            // 捕获输出用于保存结果
            std::cout.rdbuf(captured_output.rdbuf());
            test.run_concurrent_test(num_players, requests_per_second, test_duration_seconds);
            std::cout.rdbuf(orig_cout);
            
            // 显示结果
            std::cout << captured_output.str();
            
            // 保存结果到文件
            std::string filename = "concurrent_test_results_" + get_timestamp() + ".txt";
            save_results_to_file(filename, captured_output.str());
        }
        
    } catch (const std::exception& e) {
        std::cerr << "Test failed with exception: " << e.what() << std::endl;
        return 1;
    }
    
    test.cleanup();
    
    std::cout << "\n=== Test Completed ===" << std::endl;
    std::cout << "Thank you for using the HTTP Library Concurrent Player Performance Test!" << std::endl;
    
    return 0;
}